Reflect
chenpeng 2020-11-30 ES6 API
# 1.概念
Reflect 是 ES6 为了操作对象而新增的 API,它是一个全局的对象,原型是 Object(Reflect 的 API 与 Proxy 的相同)
# 2.作用
- 将 Object 对象的一些明显属于语言内部的方法(比如 Object.defineProperty),放到 Reflect 对象上,以后就可以从 Reflect 对象上拿到语言内部的方法
- 在使用对象的 Object.defineProperty(obj, name, {}) 时,如果出现异常的话,会抛出一个错误,需要使用 try... catch 去捕获,但是使用 Reflect.defineProperty(obj, name, desc) 则会返回 false
try {
Object.defineProperty(target, property, attributes);
} catch(e) {
// 失败
}
// 新写法
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 3.Reflect 方法
get() 方法用于获取对象的属性值,接受参数如下:
- target:目标对象
- key:被获取的属性名
- receiver:上下文 this 对象
const person = {
name: 'zhangsan'
};
console.log(Reflect.get(person, 'name')); // zhangsan
1
2
3
4
2
3
4
set() 方法用于设置对象的属性值,接受参数如下:
- target:目标对象
- key:被获取的属性名
- value:新属性值
- receiver:上下文 this 对象
该方法返回一个布尔值,表示属性是否设置成功
const person = {
name: 'zhangsan'
};
const result = Reflect.set(person, 'name' ,'zhaosi');
console.log(person); // zhaosi
console.log(result); // true
1
2
3
4
5
6
2
3
4
5
6